package couk.mmtdigital.sm.view
{
	import caurina.transitions.Tweener;
	
	import couk.mmtdigital.sm.ApplicationFacade;
	
	import mx.events.FlexEvent;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

	public class ApplicationMediator extends Mediator implements IMediator
	{
		public static const NAME:String = "ApplicationMediator";
		
		public function ApplicationMediator(vc:Object=null)
		{
			super(NAME, vc);
		}
		
		private function onMainView(evt:FlexEvent):void{
			spreadSheetManager.mainView.y = 0-spreadSheetManager.mainView.height;
			Tweener.addTween(spreadSheetManager.mainView, {y:10, time:1, transition:"easeOutBack",
				onStart:function():void{
					trace("mainView height: "+spreadSheetManager.mainView.height);
				},
				onComplete:function():void{
					sendNotification(ApplicationFacade.FILELIST);
					facade.registerMediator(new MainViewMediator(spreadSheetManager.mainView));
					facade.registerMediator(new FilePanelMediator(spreadSheetManager.mainView.filePn));
				}}
			);
		}
		
		override public function listNotificationInterests():Array{
			return[
				ApplicationFacade.LOGGED, 
				ApplicationFacade.LOGGEDOUT
			];
		}
		
		override public function handleNotification(notification:INotification):void{
			switch(notification.getName()){
				case ApplicationFacade.LOGGED:
					Tweener.addTween(spreadSheetManager.loginView, {y:(0-spreadSheetManager.loginView.height-10), time:1,
						transition:"easeInBack",
						onComplete:function():void{
							spreadSheetManager.currentState = "main";
							if(spreadSheetManager.mainView.height == 0)
								spreadSheetManager.mainView.addEventListener(FlexEvent.CREATION_COMPLETE, onMainView);
							else{
								Tweener.addTween(spreadSheetManager.mainView, {y:10, time:1, transition:"easeOutBack",
									onComplete:function():void{
										sendNotification(ApplicationFacade.FILELIST);
										facade.registerMediator(new MainViewMediator(spreadSheetManager.mainView));
										facade.registerMediator(new FilePanelMediator(spreadSheetManager.mainView.filePn));
									}});
							}
						}});
					break;
				case ApplicationFacade.LOGGEDOUT:
					Tweener.addTween(spreadSheetManager.mainView, {y:(0-spreadSheetManager.mainView.height-10), time:1,
						transition:"easeInBack",
						onComplete:function():void{
							spreadSheetManager.currentState = "login";
							Tweener.addTween(spreadSheetManager.loginView, {y:10, time:1, transition:"easeOutBack", 
								onComplete:function():void{
									facade.removeMediator(MainViewMediator.NAME);
									facade.removeMediator(FilePanelMediator.NAME);
								}});
						}});
			}
		}
		
		private function get spreadSheetManager():SpreadsheetManager{
			return viewComponent as SpreadsheetManager;
		}
	}
}